/**
 * Copyright (C) 2022
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，项目使用请保留此说明
 */
package com.joolun.tennis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.joolun.tennis.config.ClassOrderInfoEnum;
import com.joolun.tennis.config.CommonConstants;
import com.joolun.tennis.domain.ClassOrderInfo;
import com.joolun.tennis.domain.ClassOrderItem;
import com.joolun.tennis.domain.TennisClass;
import com.joolun.tennis.mapper.ClassOrderInfoMapper;
import com.joolun.tennis.service.ClassOrderInfoService;
import com.joolun.tennis.service.ClassOrderItemService;
import com.joolun.tennis.service.TennisClassService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商城订单
 *
 * @author JL
 * @date 2019-09-10 15:21:22
 */
@Slf4j
@Service
@AllArgsConstructor
public class ClassOrderInfoServiceImpl extends ServiceImpl<ClassOrderInfoMapper, ClassOrderInfo> implements ClassOrderInfoService {

	private final TennisClassService tennisClassService;

	private final RedisTemplate<String, String> redisTemplate;

	private final ClassOrderItemService classOrderItemService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateById(ClassOrderInfo entity) {
//		if(StrUtil.isNotBlank(entity.getLogistics()) && StrUtil.isNotBlank(entity.getLogisticsNo())){//发货。更新快递单号
//			entity.setDeliveryTime(LocalDateTime.now());
//			OrderLogistics orderLogistics = orderLogisticsService.getOne(Wrappers.<OrderLogistics>lambdaQuery()
//					.eq(OrderLogistics::getId,entity.getLogisticsId()));
//			//第一次发货调起收到倒计时
//			boolean sendRedis = false;
//			if(StrUtil.isBlank(orderLogistics.getLogistics()) && StrUtil.isBlank(orderLogistics.getLogisticsNo())){
//				sendRedis = true;
//			}
//			orderLogistics.setLogistics(entity.getLogistics());
//			orderLogistics.setLogisticsNo(entity.getLogisticsNo());
//			orderLogistics.setStatus(OrderLogisticsEnum.STATUS_1.getValue());
//			orderLogisticsService.updateById(orderLogistics);
//			if(sendRedis){
//				//加入redis，7天后自动确认收货
//				String keyRedis = String.valueOf(StrUtil.format("{}:{}",MallConstants.REDIS_ORDER_KEY_STATUS_2,entity.getId()));
//				redisTemplate.opsForValue().set(keyRedis, entity.getOrderNo() , MallConstants.ORDER_TIME_OUT_2, TimeUnit.DAYS);//设置过期时间
//			}
//		}
		return super.updateById(entity);
	}

	@Override
	public IPage<ClassOrderInfo> page1(IPage<ClassOrderInfo> page, Wrapper<ClassOrderInfo> queryWrapper) {
		return baseMapper.selectPage1(page,queryWrapper.getEntity());
	}

	@Override
	public IPage<ClassOrderInfo> page2(IPage<ClassOrderInfo> page, ClassOrderInfo orderInfo) {
		return baseMapper.selectPage2(page,orderInfo);
	}

	@Override
	public ClassOrderInfo getById2(Serializable id) {
		ClassOrderInfo orderInfo = baseMapper.selectById2(id);
		if(orderInfo != null){
			String keyRedis = null;
			//获取自动取消倒计时
			if(CommonConstants.NO.equals(orderInfo.getIsPay())){
				keyRedis = String.valueOf(StrUtil.format("{}:{}", CommonConstants.REDIS_ORDER_KEY_IS_PAY_0,orderInfo.getId()));
			}
			//获取自动收货倒计时
			if(ClassOrderInfoEnum.STATUS_2.getValue().equals(orderInfo.getStatus())){
				keyRedis = String.valueOf(StrUtil.format("{}:{}",CommonConstants.REDIS_ORDER_KEY_STATUS_2,orderInfo.getId()));
			}
			if(keyRedis != null){
				Long outTime = redisTemplate.getExpire(keyRedis);
				if(outTime != null && outTime > 0){
					orderInfo.setOutTime(outTime);
				}
			}
		}
		return orderInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void orderCancel(ClassOrderInfo orderInfo) {
		if(CommonConstants.NO.equals(orderInfo.getIsPay()) && !ClassOrderInfoEnum.STATUS_5.getValue().equals(orderInfo.getStatus())){//校验
			orderInfo.setStatus(ClassOrderInfoEnum.STATUS_5.getValue());
			//回滚库存
			List<ClassOrderItem> listOrderItem = classOrderItemService.list(Wrappers.<ClassOrderItem>lambdaQuery()
					.eq(ClassOrderItem::getOrderId,orderInfo.getId()));
			listOrderItem.forEach(orderItem -> {
				TennisClass tennisClass = tennisClassService.getById(orderItem.getClassId());
				if (tennisClass != null) {
					tennisClass.setStock(tennisClass.getStock() + orderItem.getQuantity());
					tennisClassService.updateById(tennisClass);//更新回滚库存
				}
			});
			baseMapper.updateById(orderInfo);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean removeById(Serializable id) {
		return super.removeById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void notifyOrder(ClassOrderInfo orderInfo) {
		if(CommonConstants.NO.equals(orderInfo.getIsPay())){//只有未支付订单能操作
			orderInfo.setIsPay(CommonConstants.YES);
			orderInfo.setStatus(ClassOrderInfoEnum.STATUS_1.getValue());
			List<ClassOrderItem> listOrderItem = classOrderItemService.list(Wrappers.<ClassOrderItem>lambdaQuery()
					.eq(ClassOrderItem::getOrderId,orderInfo.getId()));
			Map<String, List<ClassOrderItem>> resultList = listOrderItem.stream().collect(Collectors.groupingBy(ClassOrderItem::getClassId));
			List<TennisClass> listTennisClasses = tennisClassService.listByIds(resultList.keySet());
			listTennisClasses.forEach(goodsSpu -> {
				resultList.get(goodsSpu.getId()).forEach(orderItem -> {
					//更新销量
					goodsSpu.setSaleNum(goodsSpu.getSaleNum()+orderItem.getQuantity());
				});
				tennisClassService.updateById(goodsSpu);
				baseMapper.updateById(orderInfo);//更新订单
			});
		}
	}

}
